<template>
  <div class="earnings-management">
    <div class="page-header">
      <h2 class="page-title">收益管理</h2>
    </div>

    <!-- 筛选区域（超级管理员和普通管理员共用） -->
    <el-card class="filter-card" shadow="always">
      <el-form :inline="true" :model="searchForm" class="search-form" @submit.prevent>
        <el-form-item label="订单ID" :label-width="labelWidth">
          <el-input
              v-model.number="searchForm.orderId"
              placeholder="订单ID"
              clearable
              size="small"
              @keyup.enter="fetchFilteredEarnings"
          />
        </el-form-item>
        <el-form-item label="开始时间" :label-width="labelWidth">
          <el-date-picker
              v-model="searchForm.startTime"
              type="datetime"
              placeholder="开始时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              size="small"
              @change="fetchFilteredEarnings"
          />
        </el-form-item>
        <el-form-item label="结束时间" :label-width="labelWidth">
          <el-date-picker
              v-model="searchForm.endTime"
              type="datetime"
              placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              size="small"
              @change="fetchFilteredEarnings"
          />
        </el-form-item>
        <el-form-item label="订单类型" :label-width="labelWidth">
          <el-select
              v-model="searchForm.orderType"
              placeholder="订单类型"
              clearable
              size="small"
              @change="fetchFilteredEarnings"
          >
            <el-option label="全部" value="" />
            <el-option label="加盟商家" value="merchant" />
            <el-option label="平台自营" value="self_service" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="fetchFilteredEarnings" :loading="loading">筛选</el-button>
          <el-button size="small" @click="resetFilters">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 超级管理员视图 -->
    <div v-if="isSuperAdmin" class="super-admin-view">
      <div class="summary">
        <el-card class="summary-card" shadow="hover">
          <h3>平台总收益</h3>
          <p>{{ formatCurrency(platformTotalEarnings) }}</p>
        </el-card>
        <el-card class="summary-card" shadow="hover">
          <h3>所有商家总收益</h3>
          <p>{{ formatCurrency(merchantTotalEarnings) }}</p>
        </el-card>
      </div>

      <el-card class="table-card" shadow="always">
        <el-table
            :data="earnings"
            border
            v-loading="loading"
            style="width: 100%"
            empty-text="暂无收益数据"
        >
          <el-table-column prop="orderId" label="订单ID" width="100" sortable />
          <el-table-column prop="orderType" label="订单类型" width="120">
            <template #default="scope">
              {{ formatOrderType(scope.row.orderType) }}
            </template>
          </el-table-column>
          <el-table-column prop="merchantId" label="商家ID" width="100">
            <template #default="scope">
              {{ scope.row.merchantId || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="userId" label="用户ID" width="100" />
          <el-table-column prop="platformEarnings" label="平台收益" width="120">
            <template #default="scope">
              {{ formatCurrency(scope.row.platformEarnings) }}
            </template>
          </el-table-column>
          <el-table-column prop="merchantEarnings" label="商家收益" width="120">
            <template #default="scope">
              {{ formatCurrency(scope.row.merchantEarnings) }}
            </template>
          </el-table-column>
          <el-table-column prop="pointId" label="自助点ID" width="100">
            <template #default="scope">
              {{ scope.row.pointId || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" label="创建时间" width="180" sortable>
            <template #default="scope">
              {{ formatDate(scope.row.createdAt) }}
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
              v-model:current-page="pageNum"
              :page-size="pageSize"
              :total="totalItems"
              layout="total, sizes, prev, pager, next, jumper"
              :page-sizes="[10, 20, 50, 100]"
              background
              @size-change="handleSizeChange"
              @current-change="changePage"
          />
        </div>
      </el-card>
    </div>

    <!-- 普通管理员视图 -->
    <div v-else class="regular-admin-view">
      <div class="summary">
        <el-card class="summary-card" shadow="hover">
          <h3>平台总收益</h3>
          <p>{{ formatCurrency(adminPlatformTotal) }}</p>
        </el-card>
        <el-card class="summary-card" shadow="hover">
          <h3>商家总收益</h3>
          <p>{{ formatCurrency(adminMerchantTotal) }}</p>
        </el-card>
      </div>

      <el-card class="table-card" shadow="always">
        <el-table
            :data="adminEarnings"
            border
            v-loading="loading"
            style="width: 100%"
            empty-text="暂无收益数据"
        >
          <el-table-column prop="orderId" label="订单ID" width="100" sortable />
          <el-table-column prop="orderType" label="订单类型" width="120">
            <template #default="scope">
              {{ formatOrderType(scope.row.orderType) }}
            </template>
          </el-table-column>
          <el-table-column prop="merchantId" label="商家ID" width="100">
            <template #default="scope">
              {{ scope.row.merchantId || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="userId" label="用户ID" width="100" />
          <el-table-column prop="platformEarnings" label="平台收益" width="120">
            <template #default="scope">
              {{ formatCurrency(scope.row.platformEarnings) }}
            </template>
          </el-table-column>
          <el-table-column prop="merchantEarnings" label="商家收益" width="120">
            <template #default="scope">
              {{ formatCurrency(scope.row.merchantEarnings) }}
            </template>
          </el-table-column>
          <el-table-column prop="pointId" label="自助点ID" width="100">
            <template #default="scope">
              {{ scope.row.pointId || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" label="创建时间" width="180" sortable>
            <template #default="scope">
              {{ formatDate(scope.row.createdAt) }}
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      earnings: [],
      adminEarnings: [],
      platformTotalEarnings: 0,
      merchantTotalEarnings: 0,
      adminPlatformTotal: 0,
      adminMerchantTotal: 0,
      searchForm: {
        orderId: null,
        startTime: '',
        endTime: '',
        orderType: '',
      },
      pageNum: 1,
      pageSize: 10,
      totalPages: 1,
      totalItems: 0,
      loading: false,
      labelWidth: '70px', // 统一标签宽度，便于一行显示
    };
  },
  computed: {
    adminInfo() {
      return this.$store.state.adminInfo || { username: '管理员', role: '', adminId: null };
    },
    isSuperAdmin() {
      return this.adminInfo.role === 'super';
    },
  },
  mounted() {
    this.fetchEarningsData();
  },
  methods: {
    async fetchEarningsData() {
      this.loading = true;
      try {
        if (this.isSuperAdmin) {
          await this.fetchSuperAdminData();
        } else {
          await this.fetchRegularAdminData();
        }
      } catch (error) {
        console.error('获取收益数据错误:', error);
        this.$message.error('获取收益数据失败，请检查登录状态或联系管理员');
      } finally {
        this.loading = false;
      }
    },
    async fetchSuperAdminData() {
      const token = sessionStorage.getItem('token');
      if (!token) {
        this.$message.error('未登录，请先登录');
        this.$router.push('/');
        return;
      }

      const params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        orderId: this.searchForm.orderId || null,
        startTime: this.searchForm.startTime ? new Date(this.searchForm.startTime).toISOString() : null,
        endTime: this.searchForm.endTime ? new Date(this.searchForm.endTime).toISOString() : null,
        orderType: this.searchForm.orderType || null,
      };

      const pageResponse = await axios.get('/earnings/page', {
        params,
        headers: { Authorization: `Bearer ${token}` },
      });
      this.earnings = pageResponse.data.list || [];
      this.totalPages = pageResponse.data.pages || 1;
      this.totalItems = pageResponse.data.total || 0;

      const platformTotal = await axios.get('/earnings/platform/total', {
        params: params.startTime && params.endTime ? { start: params.startTime, end: params.endTime } : {},
        headers: { Authorization: `Bearer ${token}` },
      });
      this.platformTotalEarnings = platformTotal.data || 0;

      const merchantTotal = await axios.get('/earnings/merchant/total', {
        params: params.startTime && params.endTime ? { start: params.startTime, end: params.endTime } : {},
        headers: { Authorization: `Bearer ${token}` },
      });
      this.merchantTotalEarnings = merchantTotal.data || 0;
    },
    async fetchRegularAdminData() {
      const adminId = this.adminInfo.adminId;
      const token = sessionStorage.getItem('token');

      if (!token) {
        this.$message.error('未登录，请先登录');
        this.$router.push('/');
        return;
      }

      if (!adminId) {
        this.$message.error('无法获取管理员 ID，请重新登录');
        this.$router.push('/');
        return;
      }

      const params = {
        orderId: this.searchForm.orderId || null,
        startTime: this.searchForm.startTime ? new Date(this.searchForm.startTime).toISOString() : null,
        endTime: this.searchForm.endTime ? new Date(this.searchForm.endTime).toISOString() : null,
        orderType: this.searchForm.orderType || null,
      };

      const earningsResponse = await axios.get(`/earnings/admin/${adminId}/earnings`, {
        params,
        headers: { Authorization: `Bearer ${token}` },
      });
      this.adminEarnings = earningsResponse.data || [];

      const platformTotal = await axios.get(`/earnings/admin/${adminId}/platform/total`, {
        params: params.startTime && params.endTime ? { start: params.startTime, end: params.endTime } : {},
        headers: { Authorization: `Bearer ${token}` },
      });
      this.adminPlatformTotal = platformTotal.data || 0;

      const merchantTotal = await axios.get(`/earnings/admin/${adminId}/merchant/total`, {
        params: params.startTime && params.endTime ? { start: params.startTime, end: params.endTime } : {},
        headers: { Authorization: `Bearer ${token}` },
      });
      this.adminMerchantTotal = merchantTotal.data || 0;
    },
    async fetchFilteredEarnings() {
      this.pageNum = 1; // 重置到第一页
      await this.fetchEarningsData();
    },
    resetFilters() {
      this.searchForm = { orderId: null, startTime: '', endTime: '', orderType: '' };
      this.pageNum = 1;
      this.fetchEarningsData();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.pageNum = 1;
      this.fetchSuperAdminData();
    },
    changePage(newPage) {
      this.pageNum = newPage;
      this.fetchSuperAdminData();
    },
    formatCurrency(value) {
      return value ? `¥${parseFloat(value).toFixed(2)}` : '¥0.00';
    },
    formatDate(timestamp) {
      if (!timestamp) return '-';
      return new Date(timestamp).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
      });
    },
    formatOrderType(orderType) {
      const map = {
        merchant: '加盟商家',
        self_service: '平台自营',
      };
      return map[orderType] || orderType || '-';
    },
  },
};
</script>

<style scoped>
.earnings-management {
  padding: 24px;
  background: #f5f7fa;
  min-height: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.filter-card {
  margin-bottom: 16px;
  border-radius: 8px;
  background: #fff;
  padding: 8px 16px;
}

.search-form {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
  gap: 10px;
}

.el-form-item {
  margin-bottom: 0;
  margin-right: 10px;
}

.el-form-item:last-child {
  margin-right: 0;
  flex-shrink: 0;
}

.summary {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}

.summary-card {
  flex: 1;
  padding: 2px;
  text-align: center;
  border-radius: 8px;
  background: #fff;
  transition: all 0.3s;
}

.summary-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.summary-card h3 {
  margin-bottom: 8px;
  color: #606266;
  font-size: 14px;
  font-weight: 500;
}

.summary-card p {
  font-size: 20px;
  font-weight: 700;
  color: #409eff;
}

.table-card {
  border-radius: 8px;
  background: #fff;
}

.el-table {
  border-radius: 8px;
  overflow: hidden;
}

.el-table :deep(.el-table__header-wrapper th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
}

.pagination-container {
  padding: 16px 0;
  display: flex;
  justify-content: flex-end;
}

.el-button {
  border-radius: 6px;
  transition: all 0.3s;
}

.el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.el-button[type="primary"] {
  background: #409eff;
  border-color: #409eff;
}
</style>